package StudyCode.summary.myfile;

import java.io.File;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GetRelativePath {
	private static final String BACKWARD_SLASH = "\\";
	private static final String FORWARD_SLASH = "/";
	private static final String RELATIVE_PATH_SIG = "../";

	public static void main(String[] args) {
		String filename = "E:\\迅雷下载\\test1.txt";
		String dir = "E:\\";
		System.out.println("文件 " + filename + " 到目录 " + dir + "的相对路径是:");
		System.out.println(getRelativePath(filename, dir));
	}


	private static String getRelativePath(String source, String target) {
		if (source == null || target == null) {
			return target;
		}
		File sourceFile = new File(source);
		if (!sourceFile.exists()) {
			return target;
		}
		File targetFile = new File(target);
		if (!targetFile.exists()) {
			return target;
		}
		source = switchToForwardSlashes(source);
		target = switchToForwardSlashes(target);
		int index = target.indexOf(FORWARD_SLASH);
		String container = null;
		while (index != -1) {
			container = target.substring(0, index);
			if (!source.startsWith(container + FORWARD_SLASH)) {
				break;
			}
			source = source.substring(index + 1);
			target = target.substring(index + 1);
			index = target.indexOf(FORWARD_SLASH);
		}
		index = source.indexOf(FORWARD_SLASH);
		while (index != -1) {
			target = RELATIVE_PATH_SIG + target;
			source = source.substring(index + 1);
			index = source.indexOf(FORWARD_SLASH);
		}
		return target;
	}


	private static String switchToForwardSlashes(String path) {
		path = path.replace(File.separatorChar, FORWARD_SLASH.charAt(0));
		path = path.replace(BACKWARD_SLASH.charAt(0),
				FORWARD_SLASH.charAt(0));
		return path;
	}
}
